<template>
  <div class="message-notice">
    <mu-sub-header>公告栏</mu-sub-header>
    <div v-if="noData" class="notice-list">
      <p class="mu-primary-text notice-nodata">暂时还没有任何公告哦！</p>
    </div>
    <ul v-else class="notice-list">
      <li
        v-for="item in list"
        :key="item.id"
        class="notice-item"
      >
        <!-- eslint-disable-next-line -->
        <div class="notice-content" v-html="item.content"></div>
        <div class="notice-actions">
          <template v-if="item.update_at === item.create_at">
            <span class="info-item">{{ toDatetimeString(item.create_at) }}</span>
          </template>
          <template v-else>
            <span class="info-item">最后更新：{{ toDatetimeString(item.update_at) }}</span>
            <span class="info-item">发表时间：{{ toDatetimeString(item.create_at) }}</span>
          </template>
          <span v-if="canManage && !item.preview" class="info-item">
            <a href="javascript:;" @click="handleEdit(item)">编辑</a>
          </span>
          <span v-if="canManage && !item.preview" class="info-item">
            <a href="javascript:;" @click="handleRemove(item)">删除</a>
          </span>
          <span v-if="item.preview" class="info-item">
            <span class="info-item">这是预览</span>
          </span>
        </div>
      </li>
    </ul>
    <div v-if="canManage" class="notice-input">
      <mu-sub-header>{{ editing ? '发布公告' : '编辑公告' }}</mu-sub-header>
      <div class="notice-input-box">
        <p class="mu-secondary-text">PS. 公告可以使用html标签哦</p>
        <mu-text-field
          v-model="form.content"
          full-width
          class="notice-input-text"
          placeholder="在这里输入新公告，同步生成预览"
          multi-line
          :rows="3"
          :rows-max="10"
        ></mu-text-field>
      </div>
      <div class="notice-input-submit">
        <mu-button color="success" @click="submit()">确定</mu-button>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/api'
import { mapGetters } from 'vuex'
import { parseTime } from '@/util'

const now = new Date().getTime()
const currentYear = new Date().getFullYear()

export default {
  name: 'MessageNotice',
  data() {
    return {
      source: [],
      edit: {
        editing: false,
        id: 0
      },
      form: {
        content: ''
      }
    }
  },
  computed: {
    ...mapGetters({
      can: 'currentUserHasPermissionByCode'
    }),
    canManage() {
      return this.can('messages.notice')
    },
    list() {
      const list = this.source.map(it => ({
        ...it,
        preview: false
      }))
      if (this.edit.editing) {
        const item = list.find(it => it.id === this.edit.id)
        item.preview = true
        item.content = this.form.content
      } else if (this.form.content.length > 0) {
        list.unshift({
          id: list.length,
          content: this.form.content,
          preview: true,
          create_at: now,
          update_at: now
        })
      }
      return list
    },
    noData() {
      return this.list.length <= 0
    }
  },
  created() {
    this.getNotices()
  },
  methods: {
    // 获取所有公告
    async getNotices() {
      try {
        this.source = await api.getAllNoticeMessages()
      } catch (err) {
        this.$apiCatch(err)
      }
    },
    // 发表新公告或编辑公告
    async submit() {
      if (this.edit.editing) {
        try {
          await api.editNoticeMessage(this.edit.id, this.form.content)
          this.getNotices()
          this.$toast.success('编辑成功')
          this.form.content = ''
          this.edit.editing = false
          this.edit.id = 0
        } catch (err) {
          this.$apiCatch(err)
        }
      } else {
        try {
          await api.createNoticeMessage(this.form.content)
          this.getNotices()
          this.$toast.success('发表成功')
          this.form.content = ''
        } catch (err) {
          this.$apiCatch(err)
        }
      }
    },
    // 点击编辑
    handleEdit({ id }) {
      const item = this.source.find(it => it.id === id)
      this.form.content = item.content
      this.edit.editing = true
      this.edit.id = id
      this.$toast.info('请在下方编辑')
    },
    // 点击删除
    handleRemove({ id }) {
      this.$confirm('确定删除？', '提示', {
        type: 'warning'
      }).then(async({ result }) => {
        if (result) {
          try {
            await api.removeNoticeMessage(id)
            this.getNotices()
            this.$toast.success('删除成功')
          } catch (err) {
            this.$apiCatch(err)
          }
        } else {
          this.$toast.message('已取消')
        }
      })
    },
    toDatetimeString(time) {
      const d = new Date(time)
      const format = (d.getFullYear() === currentYear) ? '{m}-{d} {h}:{i}' : '{y}-{m}-{d} {h}:{i}'
      return parseTime(time, format)
    }
  }
}
</script>

<style scoped>
.message-notice {
  padding: 12px;
}
.notice-list {
  list-style: none;
}
.notice-nodata {
  text-align: center;
}
.notice-item:first-child {
  border-top: 1px dotted #aaa;
}
.notice-item {
  padding: 16px;
  border-bottom: 1px dotted #aaa;
}
.notice-content {
  white-space: pre-wrap;
  word-break: break-all;
}
.notice-actions {
  text-align: right;
  font-size: 0.8em;
}
.info-item {
  padding: 0 4px;
}
.info-item + .info-item {
  border-left: 1px solid #aaa;
}
.notice-input-text {
  font-size: 14px;
}
.notice-input-box {
  padding: 0 16px;
}
.notice-input-submit {
  display: flex;
  flex-flow: column;
  align-items: flex-end;
  padding: 0 16px;
}

.is-phone .info-item {
  display: block;
  border-left: none;
  padding: 0 2px;
}
</style>
